package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

   @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 用户关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //参数校验
        if (dto==null||dto.getArticleId()==null||dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //远程调用查询作者的信息
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        if (apAuthor==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"作者已被锁定");
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"需要登录");
        }
        //关注/取消关注
        if (dto.getOperation().intValue()==0){//关注操作
            return followByUserId(user.getId(),apAuthor.getUserId(),dto.getArticleId());
        }else {//取消关注
            return followCancelByUserId(user.getId(),apAuthor.getUserId());
        }


    }

    /**
     * 取消关注
     * @param userId 登陆的用户ID
     * @param followUserId 当前用户关注的作者对应的ApuserID
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {
        // 删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));

        // 删除被关注的粉丝信息
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 关注作者
     * @param userId        登陆的用户ID
     * @param followUserId  当前用户关注的作者对应的ApuserID
     * @param articleId     文章ID
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer followUserId,
                                          Long articleId) {
        ApUser apUser = apUserMapper.selectById(followUserId);
        if (apUser==null ||apUser.getStatus()){
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                "当前被关注的自媒体人已被锁定");
        }
        if (userId.equals(followUserId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"自己无需关注自己");
        }

        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));
        if (apUserFollow!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已关注，无需重复关注");
        }
         apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short)1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setFollowName(apUser.getName());
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);


        // 保存作者对应的粉丝数据
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));
        if (apUserFan!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"无需重复添加粉丝");
        }
         apUserFan = new ApUserFan();
        apUserFan.setUserId(followUserId);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short)0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());
        apUserFanMapper.insert(apUserFan);

        // 异步记录用户关注行为
        //发消息
        FollowBehaviorDto followBehaviorDto =
                new FollowBehaviorDto(articleId,followUserId,userId);

        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC,
                JSON.toJSONString(followBehaviorDto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
